package com.atguigu.gmall.payment.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.atguigu.gmall.payment.config.properties.AlipayProperties;
import com.atguigu.gmall.payment.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;


/**
 * @Author:lyd
 * @Date:2023/9/6 19:45
 * @Version:1.0
 * @Description
 **/
@Service
public class PayServiceImpl implements PayService {

    @Autowired
    AlipayProperties alipayProperties;

    @Autowired
    OrderFeignClient orderFeignClient;

    @Override
    public String getPayPage(Long orderId) throws AlipayApiException {
        //1、获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayProperties.getGatewayUrl(),
                alipayProperties.getAppId(),
                alipayProperties.getMerchantPrivateKey(),
                "json",
                alipayProperties.getCharset(),
                alipayProperties.getAlipayPublicKey(),
               alipayProperties.getSignType());

        //2、设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //设置两个回调，支付成功后浏览器会自动跳到return_url的地址。同时支付宝会异步通知notify_url 支付成功消息
        alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());


        //3、远程调用获取订单数据
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId).getData();

        //4、准备所有必要的支付参数
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no", orderInfo.getOutTradeNo());
        map.put("total_amount", orderInfo.getTotalAmount());
        map.put("subject", "尚品汇商城订单-" + orderInfo.getOutTradeNo());
        map.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //订单绝对超时时间。
        Date time = orderInfo.getExpireTime();  //yyyy-MM-dd HH:mm:ss
        map.put("time_expire", DateUtil.formatDate(time,"yyyy-MM-dd HH:mm:ss"));

        //5、给支付请求设置好 业务内容参数
        alipayRequest.setBizContent(JSONs.toJSONStr(map));


        //6、请求； 得到支付宝响应数据
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }
}
